package swe.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swe.article.Article;
import swe.article.ArticleBid;
import swe.article.ArticleManager;
import swe.article.Category;
import swe.user.User;
import swe.user.UserManager;

/**
 * Servlet implementation class Article
 */
@WebServlet("/Article")
public class ArticleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	ArticleManager am;
	UserManager um;

	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ArticleServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    @Override
    public void init() throws ServletException {
    	// TODO Auto-generated method stub
    	super.init();
    	
    	am = (ArticleManager) getServletContext().getAttribute("aManager");
		um = (UserManager) getServletContext().getAttribute("uManager");

    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		
		String action = request.getParameter("action");
		String id = null;
		String errorMessage = "";
		
		User user = (User) request.getSession(true).getAttribute("User");
		
		if(request.getParameter("id") != null) {
			id = request.getParameter("id");
		}
	
		
		if(action != null) {

			if(action.equals("view")) {
				
				request.setAttribute("article", (Article) am.getArticle(id));
				request.setAttribute("errorMessage", errorMessage);
				RequestDispatcher view = request.getRequestDispatcher("viewArticle.jsp");
				view.forward(request, response);
				
			} else if (action.equals("listFinishedArticles")) {
				if(request.getSession(true).getAttribute("isLoggedIn") != null && (Boolean) request.getSession(true).getAttribute("isLoggedIn") == true) {
					request.setAttribute("articleList", am.listFinishedArticlesForUser(user));
					
					RequestDispatcher view = request.getRequestDispatcher("listFinishedArticles.jsp");
					view.forward(request, response);
				} else {
					RequestDispatcher view = request.getRequestDispatcher("login.jsp");
					view.forward(request, response);				
				}
				
			} else if (action.equals("listCreatedArticles")) {
				if(request.getSession(true).getAttribute("isLoggedIn") != null && (Boolean) request.getSession(true).getAttribute("isLoggedIn") == true) {
					
					request.setAttribute("articleList", am.listCreatedArticlesForUser(user));
					
					RequestDispatcher view = request.getRequestDispatcher("listCreatedArticles.jsp");
					view.forward(request, response);
				} else {
					RequestDispatcher view = request.getRequestDispatcher("login.jsp");
					view.forward(request, response);				
				}
			}
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String action = request.getParameter("action");
		String errorMessage = "";
		
		/**
		 * creates a new article
		 */
		
		User user = (User) request.getSession().getAttribute("User");
		
		if(action.equals("new")) {
			if(request.getSession(true).getAttribute("isLoggedIn") != null && (Boolean) request.getSession(true).getAttribute("isLoggedIn") == true) {
				
				boolean type = (request.getParameter("articleType").equals("auction")) ? true : false;
					
				Article a = new Article(user,
						request.getParameter("title"),
							request.getParameter("description"), 
							request.getParameter("image"), 
							Double.parseDouble(request.getParameter("startprice")),
							Category.getCategoryFromId(Integer.parseInt(request.getParameter("category"))),
							type,
							Integer.parseInt(request.getParameter("runningTime"))
							);
					
				am.addArticle(a);
				
				request.setAttribute("article", a);
				request.setAttribute("errorMessage", errorMessage);
				RequestDispatcher view = request.getRequestDispatcher("viewArticle.jsp");
				view.forward(request, response);
			} else {
				RequestDispatcher view = request.getRequestDispatcher("login.jsp");
				view.forward(request, response);				
			}
			
		/**
		 * adds a bid
		 */
			
		} else if(action.equals("addBid")) {
			
			if(request.getSession(true).getAttribute("isLoggedIn") != null && (Boolean) request.getSession(true).getAttribute("isLoggedIn") == true) {
			
				String id = request.getParameter("id");
				String bidValue = request.getParameter("bidValue");
				
				if(id != null) {
					Article a = am.getArticle(id);
					
					if(a.isActive() == false) {
						errorMessage = "Auktion ist leider abgelaufen";
					} else if(user.getUserName().equals(a.getUser().getUserName())) {
						errorMessage = "Auf eigene Auktionen kann nicht geboten werden";
					} else if(!bidValue.equals("")) {	
						
						try {
							double bid = Double.parseDouble(bidValue);
							
							double highestBid = a.getHighestBid();
							
							if(bid > highestBid) {
								am.addBid(a, new ArticleBid(bid, user) );
							} else {
								errorMessage = "Gebot muss h&ouml;her sein wie "+highestBid;
							}
						} catch(NumberFormatException e) {
							errorMessage = "Bitte eine Zahl eingeben";
						}
					} else {
						errorMessage = "Bitte ein Gebot eingeben";
					}
					
					request.setAttribute("article", a);
					request.setAttribute("errorMessage", errorMessage);
					RequestDispatcher view = request.getRequestDispatcher("viewArticle.jsp");
					view.forward(request, response);
				} 
			} else {
				RequestDispatcher view = request.getRequestDispatcher("login.jsp");
				view.forward(request, response);
			}
	
		} else if (action.equals("buy")){
			// errorMessage = "ArtServ BUY TRY";

			if(request.getSession(true).getAttribute("isLoggedIn") != null && (Boolean) request.getSession(true).getAttribute("isLoggedIn") == true) {
				
				String id = request.getParameter("article");

				if(id != null) {
					Article a = am.getArticle(id);
					
					if(a.isActive() == false) {
						errorMessage = "Artikel ist leider bereits verkauft oder abgelaufen";
					} else {	
						System.out.println("mee buy now");
							am.addBuy(a, user);
					} 
					
					request.setAttribute("article", a);
					request.setAttribute("errorMessage", errorMessage);
					RequestDispatcher view = request.getRequestDispatcher("viewArticle.jsp");
					view.forward(request, response);
				} 
			} else {
				RequestDispatcher view = request.getRequestDispatcher("login.jsp");
				view.forward(request, response);
			}		
						
		} else if (action.equals("addRating")){
			
			System.out.println("ArticleServlet has addRating called, NICE");
			// String errorMessage = "";
			
			if(request.getSession(true).getAttribute("isLoggedIn") != null && (Boolean) request.getSession(true).getAttribute("isLoggedIn") == true) {
				
				String tmpArticleId = request.getParameter("articleID");
				Article tmpArticle = am.getArticle(tmpArticleId);
				
				int fromuserId = Integer.parseInt(request.getParameter("userID"));
				User fromuser = um.getUserById(fromuserId);
				
				System.out.println("ArticleServle: tmpArticle is " + tmpArticle);
				System.out.println("ArticleServle: fromuser is " + fromuser);

				
				Double tmpRatingDouble = null;
				try {
					
					tmpRatingDouble = Double.parseDouble(request.getParameter("star"));
					// System.out.println("ArticleServle: holte den stern " + );
					System.out.println("ArticleServle: rating read in");
					
					tmpArticle.addRating(tmpRatingDouble, fromuser);
					
					
				} catch (Exception e){
					errorMessage = "Sie haben eine Bewertung ohne Wert abgegeben";
				}
				
				request.setAttribute("errorMessage", errorMessage);
				request.setAttribute("articleList", am.listFinishedArticlesForUser(user));
				
				RequestDispatcher view = request.getRequestDispatcher("listFinishedArticles.jsp");
				view.forward(request, response);
				
			} else {
				RequestDispatcher view = request.getRequestDispatcher("login.jsp");
				view.forward(request, response);
			}		
		}
	}
}
